package fatboy.communication;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
//import java.lang.reflect.Method;
import java.net.Socket;
import java.net.UnknownHostException;

import fatboy.hypeerweb.Node;

public class RemoteLocation implements Location, Serializable {
	private ObjectID objID;
	private Socket sock;
	
	public RemoteLocation(ObjectID spot){
		//System.out.println(spot.getPort());
		this.objID = spot;
	}
	
	public RemoteLocation(String comp, String portNumber) {
		objID = new ObjectID(comp,0,new PortNumber(Integer.parseInt(portNumber)));
	}

	public ObjectID getObjID() {
		return objID;
	}
	
	/**
	 * sends a command to the file to be executed
	 * @param o Command to be executed by the file 
	 */
	public void sendCommand(Command o){
		try {

			sock = new Socket(objID.getComputer(), objID.getPort().getPort());
			ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
			out.reset();
			out.writeObject(o);
			out.flush();
			
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
        //System.out.println("Connection to Server succesful!");
	}
	
	public Object recieveReturn(){
	
			Object ret = null;
			try {
				ObjectInputStream in = new ObjectInputStream(sock.getInputStream());
				ret = in.readObject();
				
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
	
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			close();
			return ret;
	}
	/**
	 * closes the socket
	 */
	public void close() {
		if(sock == null)
			return;
			//sock.close();
			//System.out.println("*-- Close connection --*\n");
				
	}


	public boolean isHere() {
		String computer = "";
		try {
			computer = java.net.InetAddress.getLocalHost().getHostName();
			//System.out.println(portNumber);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		PortNumber port = PortNumber.getRuntimePort();
		return computer.equals(objID.getComputer())&& port.equals(objID.getPort());
	}
	
}
